/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import GUI.JFrameBase;
import java.text.ParseException;
import java.util.*;
import javax.swing.JOptionPane;
import libraries.LanguageLibrary;
import model.DB2Hash;

/**
 *
 * @author aeguzkiza
 */
public class StudyPanelView {
    // Text by default
    private String fieldNames = "\n- Nombre de estudio \n- Fecha de estudio\n- Parámetros de refracción\n- Realizador de la prueba\n- Patrón de la prueba\n- Modo de la prueba\n- Estrategia de la prueba\n- Parámetros de fijación\n- Parámetros del estímulo\n- Parámetros de iluminación de fondo";
    /*private String studyExists = "Ya existe un estudio con este identificador";
    private String newStudy = "Identificador nuevo en la base de datos";*/

    // Initialize variables
    public boolean isNew;
    LanguageLibrary LLib = new LanguageLibrary();
    private final JFrameBase frame;

    // Default values:
    //private String StimulusArea_text;
    //private String StimulusArea_text = "III";   // Default value
    private int Stimulus1;
    //private int Stimulus1 = 3;    // Default value

    public StudyPanelView(JFrameBase frame) {
        this.frame = frame;
    }

    public void updateViewDeletePhysicianList() {
        System.out.println("Physician combobox component count: "+frame.PerformingPhysicianNameComboBox.getComponentCount());
        if(frame.PerformingPhysicianNameComboBox.getComponentCount() != 0){
            frame.PerformingPhysicianNameComboBox.removeAllItems();
            frame.PerformingPhysicianNameComboBox1.removeAllItems();
        }
    }
    public void updateViewAddPhysician(DB2Hash p) {        
        Physician physician = new Physician(p);                     // Creates a Physician type object to manage the combobox.
        /*if(frame.PerformingPhysicianNameComboBox.getItemCount() == 0){    // Add a null value at first place.
            frame.PerformingPhysicianNameComboBox.addItem(null);
            frame.PerformingPhysicianNameComboBox1.addItem(null);
        }*/
        frame.PerformingPhysicianNameComboBox.addItem(physician);   // Attending physician:
        frame.PerformingPhysicianNameComboBox1.addItem(physician);   
    }
    
    public void updateStudyData(DB2Hash s, DB2Hash p) throws ParseException {
        this.isNew = false;
        
        frame.StudyNameInput.setText(s.get("StudyId"));
        
        String Revised = s.get("Revised");   // Checks if it's not a scheduled date.
        
        System.out.println("Revised: "+Revised+" UID: "+s.get("StudyInstanceUID"));
        
        Date date;
        if(Revised.equals("1")){
            String StudyDate = frame.parseDate(s.get("StudyDate")); // Assigns performed date value.
            //frame.StudyDateInput.setText(StudyDate);
            date = frame.dateFormat.parse(StudyDate);
        }else{
            //frame.StudyDateInput.setText(frame.parseDate(null));    // Assigns today's date value.
            date = frame.dateFormat.parse(frame.parseDate(null));     // Assigns today's date value.       
        }
        frame.StudyDateInput.setDate(date);
        
        // Clinic data previous to the test:
        frame.RxRightEyeInput1.setText(s.get("SphericalLensPower_RightEye"));
        frame.RxRightEyeInput2.setText(s.get("CylinderLensPower_RightEye"));
        frame.RxRightEyeInput3.setText(s.get("CylinderAxis_RightEye"));
        frame.RxLeftEyeInput1.setText(s.get("SphericalLensPower_LeftEye"));
        frame.RxLeftEyeInput2.setText(s.get("CylinderLensPower_LeftEye"));
        frame.RxLeftEyeInput3.setText(s.get("CylinderAxis_LeftEye"));

        frame.StudyDescriptionTextArea.setText(s.get("StudyDescription"));
        
        // Performing Physicians selection:
        if(!p.get("Id").isEmpty()){ // Comparing Physician's objects from DB2Hash.
            Physician physician = new Physician(p);
            frame.PerformingPhysicianNameComboBox.setSelectedItem(physician);   // setSelectedItem function modifyed in Physician.                        
        }else{frame.PerformingPhysicianNameComboBox.setSelectedIndex(0);}


        // Kind of test definition:
        String TestpatternsCodeSequence = s.get("TestpatternsCodeSequence");        
        frame.TestPatternsComboBox.setSelectedItem(TestpatternsCodeSequence);
        String ScreeningTestModeCodeSequence = s.get("ScreeningTestModeCodeSequence");
        frame.TestModesComboBox.setSelectedItem(ScreeningTestModeCodeSequence);
        String TestStrategyCodeSequence = s.get("TestStrategyCodeSequence");
        frame.TestStrategyComboBox.setSelectedItem(TestStrategyCodeSequence);

        // Perimeter configuration parameters:
        String FixationMonitoringCodeSequence = s.get("FixationMonitoringCodeSequence");
        if(FixationMonitoringCodeSequence.isEmpty()){FixationMonitoringCodeSequence = frame.defaultFixationStrategy;}
        frame.FixationStrategyComboBox.setSelectedItem(FixationMonitoringCodeSequence);
        /*String FixationTarget = s.get("FixationTarget");
        frame.FixationTargetComboBox.setSelectedItem(FixationTarget);*/
        String StimulusArea_string = s.get("StimulusArea");

        String StimulusArea_text = null;
        if(StimulusArea_string.length() != 0){  // In case of empty study, avoids an error trying to parseInt an empty value.
            int StimulusArea = Integer.parseInt(StimulusArea_string);            
            switch(StimulusArea){
                case (1): StimulusArea_text = "I";
                          break;
                case (2): StimulusArea_text = "II";
                          break;
                case (3): StimulusArea_text = "III";
                          break;
                case (4): StimulusArea_text = "IV";
                          break;
                case (5): StimulusArea_text = "V";
                          break;
            } 
        }else{StimulusArea_text = frame.defaultStimulusSize;}
        frame.StimulusComboBox1.setSelectedItem(StimulusArea_text);
        String StimulusColorCodeSequence = s.get("StimulusColorCodeSequence");
        if(StimulusColorCodeSequence.isEmpty()){StimulusColorCodeSequence = frame.defaultStimulusColor;}
        frame.StimulusComboBox2.setSelectedItem(StimulusColorCodeSequence);
        String BackgroundLuminance = s.get("BackgroundLuminance");
        if(BackgroundLuminance.isEmpty()){BackgroundLuminance = frame.defaultBackgruondLuminance;}
        frame.BackgroundLuminanceComboBox1.setSelectedItem(BackgroundLuminance);
        String BackgroundIlluminationColorCodeSequence = s.get("BackgroundIlluminationColorCodeSequence");        
        if(BackgroundIlluminationColorCodeSequence.isEmpty()){BackgroundIlluminationColorCodeSequence = frame.defaultBackgruondColor;}
        frame.BackgroundLuminanceComboBox2.setSelectedItem(BackgroundIlluminationColorCodeSequence);

        frame.StudyCommentsTextArea.setText(s.get("StudyComments"));
    }
    public DB2Hash getStudyData(ArrayList<String> keys, String UIDprefix) {
        this.isNew = false;
        DB2Hash study = new DB2Hash();
        
        //ArrayList patient = new ArrayList();
        System.out.println("START OF Get Study Data");
        String Id = null;
        //String StudyDate = frame.StudyDateInput.getText();
        Date studyDate = frame.StudyDateInput.getDate();
                
        String StudyDate = "";        
        if(studyDate != null){  // If studyDate is NULL, formatter will show an error.
            StudyDate = frame.dateFormat.format(studyDate); 
        }
        
        
        String StudyName = frame.StudyNameInput.getText();
        if(StudyName.isEmpty()){    // StudyName is edited only once.
            // UID = DICOMprefix + StudyDate + random number.
            this.isNew = true;
            Random randomGenerator = new Random();
            String random = Integer.toString(randomGenerator.nextInt(frame.randomMargin));
            StudyName = StudyDate+random;
            StudyName = StudyName.replaceAll("/", "");
            //frame.StudyNameInput.setText(StudyName);    // Don't write study UID until study had been saved into database.
            System.out.println("Generated random Name: "+StudyName);
        }
        String UID = UIDprefix+"."+StudyName;

        String RxRightEye1 = frame.RxRightEyeInput1.getText();
        String RxRightEye2 = frame.RxRightEyeInput2.getText();
        String RxRightEye3 = frame.RxRightEyeInput3.getText();

        String RxLeftEye1 = frame.RxLeftEyeInput1.getText();
        String RxLeftEye2 = frame.RxLeftEyeInput2.getText();
        String RxLeftEye3 = frame.RxLeftEyeInput3.getText();

        String StudyDescription = frame.StudyDescriptionTextArea.getText(); // No se ha implementado en BD!!!
        boolean PerformingPhysician = false;
        if(frame.PerformingPhysicianNameComboBox.getSelectedItem() != null){PerformingPhysician = true;}
        
        String TestPatterns = (String) frame.TestPatternsComboBox.getSelectedItem();
        String TestStrategy = (String) frame.TestStrategyComboBox.getSelectedItem();
        String TestModes = (String) frame.TestModesComboBox.getSelectedItem();
        

        String FixationStrategy = (String) frame.FixationStrategyComboBox.getSelectedItem();
        //String FixationTarget = (String) frame.FixationTargetComboBox.getSelectedItem();  // Not found in DICOM standard.

        String StimulusArea = (String) frame.StimulusComboBox1.getSelectedItem();  // Stimulus area.
        // In case of empty study, assigns the default value.
        if(StimulusArea == null){Stimulus1 = 0;}
        else if(StimulusArea.equals("I")) {Stimulus1 = 1;}
        else if(StimulusArea.equals("II")) {Stimulus1 = 2;}
        else if(StimulusArea.equals("III")) {Stimulus1 = 3;}
        else if(StimulusArea.equals("IV")){Stimulus1 = 4;}
        else if(StimulusArea.equals("V")){Stimulus1 = 5;}

        String Stimulus2 = (String) frame.StimulusComboBox2.getSelectedItem();  // Stimulus color.

        String BackgroundLuminance1 = (String) frame.BackgroundLuminanceComboBox1.getSelectedItem();    // Background luminance.
        String BackgroundLuminance2 = (String) frame.BackgroundLuminanceComboBox2.getSelectedItem();    // Background color.

        String StudyComments = frame.StudyCommentsTextArea.getText();
        String Revised = "1";    // When we want to save a study in DB, means that it's revised.
        // Check for errors:        
        if(StudyDate.isEmpty() || RxRightEye1.isEmpty() ||  RxRightEye2.isEmpty() || RxRightEye3.isEmpty() || RxLeftEye1.isEmpty() || RxLeftEye2.isEmpty() || RxLeftEye3.isEmpty()
           || !PerformingPhysician || TestPatterns.length() == 0 ||  TestStrategy.length() == 0 || TestModes.length() == 0
           || FixationStrategy.length() == 0 /*|| FixationTarget.length() == 0 */||  StimulusArea.length() == 0 || Stimulus2.length() == 0
           || BackgroundLuminance1.length() == 0 || BackgroundLuminance2.length() == 0){
            JOptionPane.showMessageDialog(frame.ClinicPanel, this.frame.emptyField+fieldNames, frame.errorTxt,JOptionPane.ERROR_MESSAGE);
        }else{
        
            // Defines in order the data to insert in database (don't touch!).
            List<String> values = Arrays.asList(Id,StudyName,UID,StudyDate,RxRightEye1,RxLeftEye1,RxRightEye2,RxLeftEye2,RxRightEye3,RxLeftEye3,StudyDescription,TestPatterns,TestStrategy,TestModes,FixationStrategy,/*FixationTarget,*/Integer.toString(Stimulus1),Stimulus2,BackgroundLuminance1,BackgroundLuminance2,StudyComments,Revised);
            //System.out.println("Keys size:"+keys.size());
            for(int i = 1; i<keys.size();i++){  // Doesn't write Id value.
                System.out.println("Keys: "+keys.get(i)+" Values: "+values.get(i));
                study.put(keys.get(i), values.get(i));
            }
        }
        return study;
    }
    public Integer getSelectedPhysicianId() {
        System.out.println("Get Physician Id");
        
        Integer idPhysician = null;
        Physician p = (Physician) frame.PerformingPhysicianNameComboBox.getSelectedItem();
        String PhysiciansFullName = p.toString();
        
        if( PhysiciansFullName.length() == 0 ){
            JOptionPane.showMessageDialog(frame.ClinicPanel, this.frame.emptyField+fieldNames, frame.errorTxt,JOptionPane.ERROR_MESSAGE);
        }else{
            idPhysician = p.getPhysicianId(); // Needs idPhysician data to associate study with physician.
                        
        }

        return idPhysician;
    }
    /*public void checkUID(int UID_exists) {
        //cambiar absolutamente TODO!
        if(UID_exists == 0){
            frame.Study_checkLabel.setText(this.studyExists);
            this.isNew = false;
        }else if(UID_exists == 1){
            // Show info message.
            String UID = frame.StudyNameInput.getText();  // Save UID value before of clear it.
            clearAll();isNew
            frame.StudyNameInput.setText(UID);    // Writes HCE value.
            frame.Study_checkLabel.setText(this.newStudy);
            this.isNew = true;

        }else{  // == 2
            //this.isNew = true;    // Has no sense, cause with empty HCE field we can't make changes over Patient data.
            frame.HCE_checkLabel.setText(null);
        }
    }*/
    public void clearAll(){
        // Clear all data.
        frame.StudyNameInput.setText(null);
        //frame.StudyDateInput.setText(null);
        frame.StudyDateInput.setDate(null);
        
        frame.RxRightEyeInput1.setText(null);
        frame.RxRightEyeInput2.setText(null);
        frame.RxRightEyeInput3.setText(null);

        frame.RxLeftEyeInput1.setText(null);
        frame.RxLeftEyeInput2.setText(null);
        frame.RxLeftEyeInput3.setText(null);

        frame.StudyDescriptionTextArea.setText(null);
        frame.PerformingPhysicianNameComboBox.setSelectedIndex(0);
        frame.TestPatternsComboBox.setSelectedIndex(0);
        frame.TestStrategyComboBox.setSelectedIndex(0);
        frame.TestModesComboBox.setSelectedIndex(0);
        frame.StudyCommentsTextArea.setText(null);

        //frame.FixationStrategyComboBox.setSelectedIndex(0);
        frame.FixationStrategyComboBox.setSelectedItem(frame.defaultFixationStrategy);

        //frame.FixationTargetComboBox.setSelectedIndex(0);

        //frame.StimulusComboBox1.setSelectedIndex(0);  // Stimulus area.
        frame.StimulusComboBox1.setSelectedItem(frame.defaultStimulusSize);
        //frame.StimulusComboBox2.setSelectedIndex(0);  // Stimulus color.
        frame.StimulusComboBox2.setSelectedItem(frame.defaultStimulusColor);

        //frame.BackgroundLuminanceComboBox1.setSelectedIndex(0);    // Background luminance.
        frame.BackgroundLuminanceComboBox1.setSelectedItem(frame.defaultBackgruondLuminance);
        //frame.BackgroundLuminanceComboBox2.setSelectedIndex(0);    // Background color.
        frame.BackgroundLuminanceComboBox2.setSelectedItem(frame.defaultBackgruondColor);
    }
    
}
